<?php
namespace app\user\validate\user\admin;

use think\Validate;

/**
 * 用户验证
 */
class Account extends Validate
{
    /**
     * 定义验证规则
     * 格式：'字段名'    =>    ['规则1','规则2'...]
     *
     * @var array
     */
    protected $rule = [
        'phone'    => 'require|mobile|checkUser',
        'password' => 'require',
    ];

    protected $field = [
        'phone'    => '手机号',
        'password' => '密码',
    ];

    /**
     * 定义错误信息
     * 格式：'字段名.规则名'    =>    '错误信息'
     *
     * @var array
     */
    protected $message = [
        'phone.require'    => '请输入手机号',
        'phone.mobile'     => '手机号码格式不正确',
        'phone.unique'     => '手机号已注册',
        'password.require' => '请输入密码',
    ];

    /**
     * 验证场景
     */
    protected $scene = [
        'add'  => ['phone', 'password'],
        'edit' => ['phone'],
    ];

    public function checkUser($value, $rule, $data)
    {
        $has   = false;
        $mhmId = $data['mhm_id'] ?? request()->mhm_id;
        if ($this->currentScene === 'add') {
            $has = \app\user\model\user\Account::where('phone', $value)->where('mhm_id', $mhmId)->value('id');
        } else if ($this->currentScene === 'edit') {
            $has = \app\user\model\user\Account::where('phone', $value)
                ->where('mhm_id', $mhmId)
                ->where('id', '<>', $data['id'])
                ->value('id');
        }

        if ($has) {
            return '手机号已注册';
        }

        return true;
    }

}
